<template>
  <card class="add-fence add-info-card car-model-999" title="编辑围栏">
    <a-button type="primary" v-if="form.rule != '1'" class="add-fence-btn" @click="addFenceModule()"> + 新增</a-button>
    <page-form :model="formFence" layout="vertical" ref="formFenceRef">
      <div v-for="(item, index) in formFence.electricFenceList" :key="item.id">
        <div class="fence-box">
          <div class="fence-tips">围栏{{ index + 1 }}</div>
          <page-form-item
            class="form-item"
            :field="`electricFenceList.${index}.fenceType`"
            :rules="formFenceRules.fenceType"
            label="围栏类型"
            required
          >
            <a-radio-group v-model="item.fenceType" class="radio-group" @change="changeRadio($event, index)">
              <a-radio :value="itemRadio.value" v-for="itemRadio in fenceDict.vehiceFenceTypeEnum" :key="itemRadio.value">
                {{ itemRadio.label }}
              </a-radio>
              <SvgIcon v-if="+item.fenceType === 2" @click="clickFenceDescription" class="fence-tips-box" name="fence-tips" />
              <span v-if="+item.fenceType === 2">
                <a-button v-if="!item.isShowEdit" class="eidt-btn" @click="handleCustomCreate(index)" type="text">
                  <span><SvgIcon name="fence-edit" /> 编辑</span>
                </a-button>
                <a-button v-else class="eidt-btn" @click="outEdit(index)" type="text">
                  <span><SvgIcon name="fence-edit" /> 保存编辑</span>
                </a-button>
              </span>
            </a-radio-group>
          </page-form-item>
        </div>
        <!-- 省市围栏 -->
        <div class="city-fence" v-if="+item.fenceType === 1">
          <page-form-item
            :field="`electricFenceList.${index}.pointProvinceCode`"
            :rules="formFenceRules.pointProvinceCode"
            label="省/市"
            required
          >
            <remote-select
              style="width: 280px"
              v-model="item.pointProvinceCode"
              mode="cascader"
              placeholder="请选择省份"
              type="area_area"
              @change="changeFenceProvince($event, index)"
            />
          </page-form-item>
          <page-form-item :field="`electricFenceList.${index}.cityCode`" :rules="formFenceRules.cityCode" label="城市">
            <remote-select
              style="width: 280px"
              v-model="item.cityCode"
              :params="{
                parentCode: item.pointProvinceCode,
              }"
              placeholder="请选择城市"
              type="area_area"
              :index="index"
              @change="changeFenceCity"
            />
          </page-form-item>
        </div>
      </div>
      <!-- 地图容器 -->
      <fence-map
        ref="fenceMapRef"
        :fenceMenuList="clickedOverlays"
        :electricFenceList="formFence.electricFenceList"
        @refreshMap="refreshMap"
        @editFence="editFence"
        @deleteFence="deleteFence"
      />
    </page-form>
    <page-form-footer cancelText="返回" :cancelFn="cancelFn" @ok="saveFenceCarModel" />
  </card>
  <fence-description-modal ref="fenceDescriptionModalRef" />
</template>
<script setup>
  import { ref, reactive, onMounted } from 'vue'
  import { usePageDict } from '@/hooks/useDict'
  import { formFenceRules } from '../options'
  import { Message, Modal } from '@arco-design/web-vue'
  import fenceMap from './fence-map.vue'
  import fenceDescriptionModal from './fence-description-modal.vue'

  const props = defineProps({
    id: String,
    form: {
      type: Object,
      default: () => {},
    },
  })
  const emit = defineEmits(['cancelFenceFn', 'submitBtn'])

  const formFence = reactive({
    electricFenceList: null,
  }) // 围栏表单
  const formFenceRef = ref() // 围栏表单校验
  const fenceDict = usePageDict('fenceDict') // 围栏类型
  const fenceMapRef = ref(null) // 地图组件ref
  const fenceList = ref([]) // 自定义围栏list
  const clickedOverlays = ref(null) // 存储点击位置处的覆盖物
  const fenceDescriptionModalRef = ref(null) // 围栏说明弹窗
  // 初始化数据
  onMounted(() => {
    const data = props.form.electricFenceList || [
      {
        fenceType: 1,
        pointProvinceCode: null,
        cityCode: null,
        mapData: null,
        storeXY: [],
        polyEditor: null,
        cityName: null,
        name: null,
        isShowEdit: false,
      },
    ]
    formFence.electricFenceList = JSON.parse(JSON.stringify(data))
  })
  // 围栏说明
  const clickFenceDescription = () => {
    fenceDescriptionModalRef.value.open()
  }
  // 编辑回显
  const refreshMap = () => {
    formFence.electricFenceList.forEach((item, index) => {
      changeFenceMap(index)
    })
  }
  //切换围栏类型
  const changeRadio = async (val, index) => {
    const electricFence = formFence.electricFenceList[index]
    const find = fenceList.value.find((o) => +o.fenceIndex === index)
    if (find) {
      fenceMapRef.value.map.remove(find.polygon)
      clearCityList(index)
      electricFence.polyEditor && electricFence.polyEditor.close()
    }
    if (val == 1) {
      electricFence.polyEditor = null
      electricFence.isShowEdit = false
    }
    changeFenceMap(index)
  }

  // 返回
  const cancelFn = () => {
    emit('cancelFenceFn')
  }
  // 编辑自定义围栏
  const handleCustomCreate = async (index) => {
    const electricFence = formFence.electricFenceList[index]
    electricFence.isShowEdit = true
    const find = fenceList.value.find((o) => +o.fenceIndex === index)
    if (find && electricFence.polyEditor && electricFence.isDrawFence) {
      electricFence.polyEditor.setTarget(find.polygon)
      electricFence.polyEditor.open()
    } else {
      await initPolyEditorAMap(index)
      electricFence.polyEditor.setTarget()
      electricFence.polyEditor.open()
    }
  }
  // 退出当前自定义围栏
  const outEdit = (index) => {
    const electricFence = formFence.electricFenceList[index]
    electricFence.isShowEdit = false
    electricFence.polyEditor.close()
  }
  // 右键编辑
  const editFence = ({ fenceIndex }) => {
    const electricFence = formFence.electricFenceList[fenceIndex]
    electricFence.isShowEdit = true
    fenceMapRef.value.showMenu = false
    const find = fenceList.value.find((o) => +o.fenceIndex === fenceIndex)
    electricFence.polyEditor.setTarget(find.polygon)
    electricFence.polyEditor.open()
  }
  // 右键删除
  const deleteFence = ({ fenceIndex, type }) => {
    Modal.confirm({
      title: '提示',
      simple: true,
      cancelText: '取消',
      okText: '确认',
      content: `请确认，是否删除当前围栏？`,
      onOk: () => {
        const electricFence = formFence.electricFenceList
        fenceMapRef.value.showMenu = false
        const find = fenceList.value.find((o) => +o.fenceIndex === fenceIndex)
        fenceMapRef.value.map.remove(find.polygon)
        if (+type === 2) {
          electricFence[fenceIndex].polyEditor.close()
        } else {
          clearCityList(fenceIndex)
        }
        fenceList.value.splice(fenceIndex, 1)
        electricFence.splice(fenceIndex, 1)
        // 刷新索引
        fenceList.value = fenceList.value.map((val, index) => {
          val.fenceIndex = index
          return val
        })
      },
      onCancel: () => {
        if (+type === 2) {
          outEdit(fenceIndex)
        }
      },
    })
  }
  // 新增自定义围栏
  const initPolyEditorAMap = (index) => {
    const electricFence = formFence.electricFenceList[index]
    electricFence.polyEditor = new AMap.PolygonEditor(fenceMapRef.value.map)

    // 新增
    electricFence.polyEditor.on('add', (data) => {
      let polygon = data.target
      electricFence.isDrawFence = true
      electricFence.polyEditor.addAdsorbPolygons(polygon)
      updataFenceList({ polygon, fenceIndex: index, type: electricFence.fenceType })
      rightChange(polygon)
    })
  }
  // 往fenceList.value同步数据
  const updataFenceList = (val) => {
    const index = fenceList.value.findIndex((obj) => obj.fenceIndex === val.fenceIndex)
    if (index !== -1) {
      fenceList.value[index] = val
    } else {
      fenceList.value.push(val)
    }
  }

  // 清理数据
  const clearData = (index) => {
    const electricFence = formFence.electricFenceList[index]
    electricFence.pointProvinceCode = null
    electricFence.cityCode = null
    electricFence.cityName = null
    electricFence.name = null
    clearCityList(index)
  }
  // 清空省下面的多个集合
  const clearCityList = (index) => {
    const electricFence = formFence.electricFenceList[index]
    electricFence.storeXY &&
      electricFence.storeXY.forEach((item) => {
        fenceMapRef.value.map.remove(item)
      })
    electricFence.storeXY = []
    electricFence.mapData && electricFence.mapData.setMap(null)
    electricFence.mapData = null
  }
  // 选择省市
  const changeFenceProvince = (val, index) => {
    const electricFence = formFence.electricFenceList[index]
    clearData(index)
    electricFence.pointProvinceCode = val
    changeFenceMap(index)
  }
  // 地图类型、城市change
  const changeFenceCity = (val, option = {}, index) => {
    const electricFence = formFence.electricFenceList[index]
    electricFence.cityName = option.name
    clearCityList(index)
    changeFenceMap(index)
  }
  // 分发
  const changeFenceMap = (index) => {
    const electricFence = formFence.electricFenceList[index]
    // 城市围栏
    if (+electricFence.fenceType === 1) {
      if (electricFence.cityCode || electricFence.pointProvinceCode) {
        cityFenceAMap(index)
      }
    } else {
      // 自定义围栏
      if (electricFence.points) {
        customFenceAMap(index)
      }
    }
  }

  // 自定义围栏 添加右键事件
  const rightChange = (polygon) => {
    polygon.on('rightclick', (event) => {
      document.addEventListener('contextmenu', (evt) => {
        evt.preventDefault()
      })
      clickedOverlays.value = []
      // 遍历所有覆盖物，判断是否包含点击位置
      for (let i = 0; i < fenceList.value.length; i++) {
        let overlay = null
        if (fenceList.value[i].storeXY) {
          // 判断省的坐标集合是单个还是多个 有值代表多个
          fenceList.value[i].storeXY.forEach((item) => {
            overlay = item
            if (overlay.contains(event.lnglat)) {
              clickedOverlays.value.push(fenceList.value[i])
            }
          })
        } else {
          overlay = fenceList.value[i].polygon
          if (overlay.contains(event.lnglat)) {
            clickedOverlays.value.push(fenceList.value[i])
          }
        }
      }
      // 获取点击位置的像素坐标
      const pixel = event.pixel
      // 将像素坐标转换为经纬度坐标
      const lnglat = fenceMapRef.value.map.pixelToLngLat(pixel)
      // 显示自定义右键菜单
      fenceMapRef.value.showCustomMenu(lnglat, pixel)
    })
  }

  // 建立多边形覆盖物
  const polyfillAddPolygon = (path) => {
    const polygon = new AMap.Polygon({
      path,
      strokeWeight: 2,
      strokeColor: '#2C72FF',
      fillColor: '#6A9CFF',
      fillOpacity: 0.3,
      zIndex: 50,
      bubble: false,
    })
    return polygon
  }
  // 回显自定义围栏
  const customFenceAMap = (index) => {
    const electricFence = formFence.electricFenceList[index]
    electricFence.polyEditor = new AMap.PolygonEditor(fenceMapRef.value.map)
    const newFenceList = JSON.parse(electricFence.points)
    const polygon = polyfillAddPolygon(newFenceList)
    updataFenceList({ polygon, fenceIndex: index, type: electricFence.fenceType })
    fenceMapRef.value.map.add(polygon)
    fenceMapRef.value.map.setFitView(null, true)
    electricFence.isDrawFence = true
    electricFence.polyEditor.addAdsorbPolygons(polygon)
    rightChange(polygon)

    // fenceList.value.forEach((polygon) => {
    //   polygon.on('dblclick', () => {
    //     fenceList.value.polygon.polyEditor.setTarget(polygon)
    //     fenceList.value.polygon.polyEditor.open()
    //   })
    // })
  }

  // 城市围栏
  const cityFenceAMap = (index) => {
    const electricFence = formFence.electricFenceList[index]
    let opts = {
      subdistrict: 1, //返回下一级行政区
      showbiz: false, //最后一级返回街道信息
      extensions: 'all',
    }
    const district = new AMap.DistrictSearch(opts) //注意：需要使用插件同步下发功能才能这样直接使用
    const areaCode = electricFence.cityCode || electricFence.pointProvinceCode
    district.search(areaCode, (status, result) => {
      if (status == 'complete') {
        const bounds = result.districtList[0].boundaries
        electricFence.storeXY = []
        for (let i = 0, l = bounds.length; i < l; i++) {
          electricFence.mapData = new AMap.Polygon({
            map: fenceMapRef.value.map,
            path: bounds[i],
            strokeWeight: 2,
            strokeColor: '#2C72FF',
            fillColor: '#6A9CFF',
            fillOpacity: 0.3,
            zIndex: 50,
            bubble: false,
          })
          electricFence.storeXY.push(electricFence.mapData)
          rightChange(electricFence.mapData)
        }
        updataFenceList({
          polygon: electricFence.mapData,
          fenceIndex: index,
          type: electricFence.fenceType,
          storeXY: electricFence.storeXY,
        })
        fenceMapRef.value.map.setFitView()
      }
    })
  }
  // 新增围栏
  const addFenceModule = () => {
    formFence.electricFenceList.push({
      fenceType: 1,
      pointProvinceCode: null,
      cityCode: null,
      mapData: null,
      polyEditor: null,
      cityName: null,
      name: null,
    })
  }

  // 保存围栏
  const saveFenceCarModel = () => {
    const electricFence = formFence.electricFenceList
    formFenceRef.value.validate((error) => {
      if (error) {
        console.log(error)
      } else {
        electricFence.forEach((val, index) => {
          const find = fenceList.value.find((o) => +o.fenceIndex === index)
          if (+val.fenceType === 1) {
            electricFence[index].points = null
          } else {
            electricFence[index].cityName = null
            electricFence[index].pointProvinceCode = null
            electricFence[index].pointProvinceName = null
            electricFence[index].cityCode = null
            electricFence[index].polyEditor = null
            if (find) {
              let fencePath = find.polygon.getPath().map((item) => [item.lng, item.lat])
              electricFence[index].points = JSON.stringify(fencePath)
            }
          }
          electricFence[index].name = +val.fenceType === 1 ? `省市围栏${index + 1}` : `自定义围栏${index + 1}`
          electricFence[index].findIndex = index + 1
        })
        // 判断新增的自定义围栏是否有空的
        const find = electricFence.find((o) => {
          return +o.fenceType === 2 && !o.points
        })
        if (find) {
          Message.warning(`围栏${find.findIndex}，未编辑围栏，请完善`)
          return
        }
        console.log('---保存围栏', electricFence)
        const submitData = electricFence.map((val) => {
          delete val.mapData
          delete val.polyEditor
          delete val.findIndex
          delete val.storeXY
          return val
        })
        emit('submitBtn', submitData)
      }
    })
  }
</script>
<style lang="less" scoped>
  .add-fence {
    position: relative;
    .add-fence-btn {
      position: absolute;
      right: 0;
      top: 5px;
    }

    .fence-box {
      position: relative;
      margin-bottom: -10px;
      .fence-tips {
        position: relative;
        width: fit-content;
        font-size: 14px;
        font-weight: bold;
        color: #1d2129;
        line-height: 22px;
        background: #f1f4fa;
        padding: 0 5px;
      }

      .form-item {
        :deep(.arco-form-item-label-col) {
          position: absolute;
          left: 60px;
          top: 0px;
        }
        :deep(.arco-form-item-wrapper-col) {
          margin-top: 10px;
        }
      }
    }
    .city-fence {
      padding: 20px 20px 0px 20px;
      box-sizing: border-box;
      display: flex !important;
      background: rgba(247, 248, 250, 0.5);
      margin-bottom: 10px;

      .city-box {
        margin-left: 20px;
      }
    }
  }

  .radio-group {
    position: relative;
  }
  .fence-tips-box {
    position: absolute;
    right: 0px;
    font-size: 16px;
    top: 4px;
  }
  .eidt-btn {
    position: absolute;
    left: 215px;
    top: -4px;
    display: flex;
    align-items: center;
    margin-left: 6px;
    font-size: 14px;
    cursor: pointer;

    span {
      display: flex;
      align-items: center;
    }
  }
</style>
